package com.fw.application.security.comm;

import cn.hutool.json.JSONUtil;
import com.fw.constant.Constant;
import com.fw.enums.CodeStatus;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.FwUser;
import com.fw.system.web.service.IFwUserService;
import com.fw.utils.AuthUtils;
import com.fw.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限过滤类
 *
 * @Author:yanwei
 * @Date: 2020/10/14 - 14:44
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private AuthUtils authUtils;

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private IFwUserService userService;

    /**
     * 内部过滤
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //得到header中权限信息
        String authHeader = request.getHeader(Constant.RequestConstant.HEAD_FLAG);
        String imei = request.getHeader("imei");
        String version = request.getHeader("version");
        String requestURI = request.getRequestURI();
        Thread.sleep(1500);
        FwUser user = new FwUser();
        if (authHeader != null && authHeader.startsWith(Constant.RequestConstant.BEARER)) {
            String authToken = authHeader.substring(Constant.RequestConstant.BEARER.length());
            String userId = null;
            try {
                userId = authUtils.parseJWT(authToken).getId();
                user = userService.getById(userId);
            } catch (Exception e) {
                log.error("当前token解析失效了");
            }
/*            if (org.apache.commons.lang3.StringUtils.isBlank(version) && Arrays.stream(SecurityConfig.permitAll()).filter(item -> requestURI.equals(item)).count() == 0) {
                throw  new RuntimeException("请去更新");
            }*/
            if (!StringUtils.isBlank(imei) && !StringUtils.isBlank(user.getImei())) {
                if (!user.getImei().equals(imei)) {
                    log.error("imei比对失败");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json");
                    response.getWriter().println(JSONUtil.parse(new Result<>(CodeStatus.ADD_NOT_LOGIN)));
                    response.getWriter().flush();
                    return;
                }
            }
            if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
/*
                ((BaseUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).get
*/
            }
        }
        filterChain.doFilter(request, response);

    }
}
